package com.massa.caronafacil.viewpager;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * The <code>PagerAdapter</code> serves the fragments when paging.
 */
public class PagerAdapter extends FragmentPagerAdapter {

    /** Holds the list of fragments. */
    private List<Fragment> mFragments;

    /**
     * @param fm
     *            the FragmentManager instance.
     * @param fragments
     *            the list of fragments.
     */
    public PagerAdapter(final FragmentManager fm, final List<Fragment> fragments) {
        super(fm);

        mFragments = fragments;
    }

    @Override
    public final Fragment getItem(final int position) {
        if ((mFragments != null) && (mFragments.size() > position)) {
            return mFragments.get(position);
        }

        return null;
    }

    @Override
    public final int getCount() {
        if (mFragments != null) {
            return mFragments.size();
        }

        return -1;
    }

    /**
     * Returns the fragment position based on its name.
     *
     * @param fragClassName
     *            the fragment class' name.
     * @return the fragment position in view pager.
     */
    public final int getItemPosition(final String fragClassName) {
        int fragmentPosition = -1;

        if (mFragments != null) {
            int index = 0;

            for (Fragment frag : mFragments) {
                if ((frag != null) && (frag.getClass().getSimpleName().equals(fragClassName))) {
                    fragmentPosition = index;
                    break;
                }

                index++;
            }
        }

        return fragmentPosition;
    }
}